﻿Imports System.Data.SqlClient

Public Class ServicioDAO


    Public Function insertar(ByVal omen As Servicio) As Servicio
        Try
            Dim cn As New SqlConnection(ConexionBD.obtenerCadenaConexion())
            cn.Open()

            Dim sql = "INSERT INTO Servicio (idUsuario, idVenta, descripcion) VALUES (@VALOR1, @VALOR2, @VALOR3)"

            Dim cmd As New SqlCommand(sql, cn)
            cmd.Parameters.AddWithValue("@VALOR1", omen.idUsuario)
            cmd.Parameters.AddWithValue("@VALOR2", omen.idventa)
            cmd.Parameters.AddWithValue("@VALOR3", omen.descripcion)

            Dim afectados = cmd.ExecuteNonQuery

            If afectados <> 1 Then
                Throw New DAOExcepcion("ServicioDAO: No insertó")
            End If

            ' LEER EL ULTIMO ID
            sql = "SELECT @@IDENTITY"
            cmd = New SqlCommand(sql, cn)
            Dim dr As SqlDataReader
            dr = cmd.ExecuteReader()
            If dr.Read Then
                omen.idServicio = CType(dr(0), Integer)
            End If

            dr.Close()
            cn.Close()

        Catch ex As Exception
            Throw New DAOExcepcion(ex.ToString)
        End Try

        Return omen

    End Function

    Public Function listar() As Collection
        Dim lista As New Collection

        Try
            Dim cn As New SqlConnection(ConexionBD.obtenerCadenaConexion())
            cn.Open()

            Dim sql = "SELECT idServicio, idUsuario, idVenta, descripcion FROM SERVICIO"
            Dim cmd As New SqlCommand(sql, cn)

            Dim dr As SqlDataReader
            dr = cmd.ExecuteReader()
            While dr.Read
                Dim omen As New Servicio
                omen.idServicio = dr(0).ToString
                omen.idUsuario = dr(1).ToString
                omen.idventa = dr(2).ToString
                omen.descripcion = dr(3).ToString


                lista.Add(omen)
            End While

            dr.Close()
            cn.Close()

        Catch ex As SqlException
            Throw New DAOExcepcion(ex.ToString)
        End Try

        Return lista
    End Function


    Public Sub eliminar(ByVal idServicio As Integer)
        Try
            Dim cn As New SqlConnection(ConexionBD.obtenerCadenaConexion())
            cn.Open()

            Dim sql = "DELETE FROM SERVICIO WHERE idServicio=@VALOR1"

            Dim cmd As New SqlCommand(sql, cn)
            cmd.Parameters.AddWithValue("@VALOR1", idServicio)

            Dim afectados = cmd.ExecuteNonQuery

            If afectados <> 1 Then
                Throw New DAOExcepcion("ServicioDAO: No eliminó")
            End If

            cn.Close()

        Catch ex As Exception
            Throw New DAOExcepcion(ex.ToString)
        End Try
    End Sub



End Class
